#include <iostream>
#include <SDL.h>
#include <unistd.h>


using namespace std;

bool init();
void kill();
bool load();
bool loop();


SDL_Window* window;
SDL_Surface* winSurface;
SDL_Surface* image1;
SDL_Surface* image2;



int main(int argc,const char* argv[]) {

    if ( !init() )   return 1;

    if ( !load() )  return 1;
    
    while ( loop() ) {
            SDL_Delay(10);

    }

    kill();

    return 0;
}



bool init()
{
    if ( SDL_Init( SDL_INIT_EVERYTHING) < 0) {
        cout << "Error initing: " << SDL_GetError() << endl;
        pause();
        return false;
    }

    window = SDL_CreateWindow( "Example", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, SDL_WINDOW_SHOWN );
    if( !window ) {
        cout << "Error creating window: " << endl;
        pause();
        return false;
    }

    winSurface = SDL_GetWindowSurface( window);

    if( !winSurface ) {
        cout << "Error getting windowsurface: " << SDL_GetError() << endl;
        pause();
        return false;
    }
    return true;
}

void kill()
{
    SDL_FreeSurface( image1);
    SDL_FreeSurface( image2);

    SDL_DestroyWindow( window);
    SDL_Quit();
    

}

bool load()
{
    SDL_Surface *temp1, *temp2;
    temp1 = SDL_LoadBMP("test1.bmp");
    temp2 = SDL_LoadBMP("test2.bmp");

    if ( !temp1 || !temp2 ) {
        cout << "Error loading image: " << SDL_GetError() << endl;
        pause();
        return false;
    }

    image1 = SDL_ConvertSurface( temp1, winSurface->format, 0);
    image2 = SDL_ConvertSurface( temp2, winSurface->format, 0);

    SDL_FreeSurface( temp1 );
	SDL_FreeSurface( temp2 );

	// Make sure format succeeded
	if ( !image1 || !image2 ) {
		cout << "Error converting surface: " << SDL_GetError() << endl;
		pause();
		return false;
	}

    if( !image1 || !image2){
        cout << "Error converting surface: " << endl;
        pause();
        return false;
    }
    
    return true;
}


bool loop()
{
    static bool renderImage2;
    SDL_Event e;

    SDL_BlitSurface( image1, NULL, winSurface, NULL );

    while( SDL_PollEvent(&e) != 0){
        switch( e.type ){
            case SDL_QUIT:
                cout << "quit: " << endl;
                return false;
            case SDL_KEYDOWN:
                renderImage2 = true;
                break;
            case SDL_KEYUP:
                renderImage2 = false;

                break;
            case SDL_MOUSEMOTION:

                break;
            
            

        }
    }

    if ( renderImage2)
    {
        SDL_Rect dest;
        dest.x = 160;
        dest.y = 120;
        dest.w = 320;
        dest.h = 240;
        SDL_BlitScaled(image2, NULL, winSurface, &dest);
    }

    SDL_UpdateWindowSurface( window);

    return true;
}